/* global window */
/* global document */
import React from 'react'
import NProgress from 'nprogress'
import PropTypes from 'prop-types'
// import pathToRegexp from 'path-to-regexp'
import { connect } from 'dva'
import { Helmet } from 'react-helmet'
import { withRouter } from 'dva/router'

import { config } from 'setting'
import { classnames } from 'utils'
import languageList from './language'

import Error from '../pages/404/index.js'
import { BackTop, Layout, LocaleProvider, Popover } from 'antd'
import { YQLoader } from 'components'
import * as YQLayout from './components/index.js'  //项目结构

import '../themes/index.less'
import './app.less'

const { Content, Sider } = Layout
const { YQHeader, YQMenu, YQProdMenu, YQBread, styles } = YQLayout
const { prefix, openPages } = config

let lastHref

const App = ({
  children, dispatch, app, loading, location,
}) => {
  const {
    user, siderFold, isNavbar, menuPopoverVisible, navOpenKeys, menu, language, headerMenus,
    spreadAbled, spreadProdMenu, prodMenubarTitle, prodNavOpenKeys, prodMenu, hasBread,
  } = app

  let { pathname } = location
  pathname = pathname.startsWith('/') ? pathname : `/${pathname}`
  const { iconFontJS, iconFontCSS, logo } = config
  
  // const current = menu.filter(item => pathToRegexp(item.route || '').exec(pathname))
  // const hasPermission = current.length ? permissions.visit.includes(current[0].id) : false
  const hasPermission = true 
  const { href } = window.location
  if (lastHref !== href) {
    NProgress.start()
    if (!loading.global) {
      NProgress.done()
      lastHref = href
    }
  }
  // 判断语言
  let localeLang, localeLangText
  languageList.map((item) => { 
    if(item.language === language) {
      localeLang = item.value
      localeLangText = item.text
    } 
    return item
  })

  // 头部
  const headerProps = {
    menu,
    user,
    location,
    siderFold,
    isNavbar,
    menuPopoverVisible,
    navOpenKeys,
    localeLangText,
    headerMenus,
    switchMenuPopover () {
      dispatch({ type: 'app/switchMenuPopover' })
    },
    logout () {
      dispatch({ type: 'app/logout' })
    },
    switchSider () {
      dispatch({ type: 'app/switchSider' })
    },
    changeOpenKeys (openKeys) {
      dispatch({ type: 'app/handleNavOpenKeys', payload: { navOpenKeys: openKeys } })
    },
    changeLang (language) {
      window.localStorage.setItem(`${prefix}language`, language)
      dispatch({ type: 'app/handleLang', payload: language })
    },
    getProdMenu (menuId) {
      dispatch({ type: 'app/getProdMenu', payload: menuId })
      dispatch({ type: 'app/switchMenuPopover' })
    },
    closeProdMenu () {
      if(spreadProdMenu) dispatch({ type: 'app/switchProdMenu' })
    },
    switchSpreadAbled (spreadAbled) {
      dispatch({ type: 'app/switchSpreadAbled', payload: spreadAbled })
    },
  }
  // 侧边主菜单
  const menuProps = {
    menu,
    location,
    siderFold,
    isNavbar,
    navOpenKeys,
    switchSider () {
      dispatch({ type: 'app/switchSider' })
    },
    changeOpenKeys (openKeys) {
      window.localStorage.setItem(`${prefix}navOpenKeys`, JSON.stringify(openKeys))
      dispatch({ type: 'app/handleNavOpenKeys', payload: { navOpenKeys: openKeys } })
    },
    getProdMenu (menuId) {
      dispatch({ type: 'app/getProdMenu', payload: menuId })
    },
    closeProdMenu () {
      if(spreadProdMenu) dispatch({ type: 'app/switchProdMenu' })
    },
    switchSpreadAbled (spreadAbled) {
      dispatch({ type: 'app/switchSpreadAbled', payload: spreadAbled })
    },
  }
  // 侧边次菜单
  const ProdMenuProps = {
	  prodMenu,
	  prodMenubarTitle,
    location,
    spreadProdMenu,
    prodNavOpenKeys,
    switchSider () {
      dispatch({ type: 'app/switchSider' })
    },
    changeOpenKeys (openKeys) {
      window.localStorage.setItem(`${prefix}prodNavOpenKeys`, JSON.stringify(openKeys))
      dispatch({ type: 'app/handleProdNavOpenKeys', payload: { prodNavOpenKeys: openKeys } })
    },
    switchProdMenu () {
      dispatch({ type: 'app/switchProdMenu' })
    },
  }

  // 面包屑
  const breadProps = {
    prodMenu,
    location,
  }

  if (openPages && openPages.includes(pathname)) {
    return (<div>
      <YQLoader fullScreen spinning={loading.effects['app/query']} />
      {children}
    </div>)
  }

  return (
    <LocaleProvider locale={localeLang}>
      <div>
        <YQLoader fullScreen spinning={loading.effects['app/query']} />
        <Helmet>
          <title>{config.name}</title>
          <meta name="viewport" content="width=device-width, initial-scale=1.0" />
          <link rel="icon" href={logo} type="image/x-icon" />
          {iconFontJS && <script src={iconFontJS} />}
          {iconFontCSS && <link rel="stylesheet" href={iconFontCSS} />}
        </Helmet>

        <Layout className={classnames({ [styles.dark]: true })}>
          <YQHeader {...headerProps} />
          <Layout style={{ height: 'calc(100vh - 50px)', overflowY: 'auto', marginTop:"50px"}} id="mainContainer">
            <BackTop target={() => document.getElementById('mainContainer')} />
            {!isNavbar && <Sider
              trigger={null}
              collapsible
              collapsed={siderFold}
              width={160}
              collapsedWidth ={50}
            >
            <Popover placement="topLeft" content={menuProps.menu}>
              {menuProps.menu.length === 0 ? null : <YQMenu {...menuProps} />}
            </Popover>
           
            </Sider>}
            <Layout className={styles.mainwrap}>
              <Sider
                width={150}
                collapsedWidth ={0}
                trigger={null}
                collapsible
                collapsed={!(spreadAbled && spreadProdMenu)}
              >
                <div className={classnames(styles.switchProdSider, { [styles.show]: spreadAbled && !spreadProdMenu })} onClick={()=>{dispatch({ type: 'app/switchProdMenu' })}}></div>
                <YQProdMenu {...ProdMenuProps} />
              </Sider>
              <Content className = {classnames(styles.productbody, {'':spreadProdMenu, [styles.fullwidth]:!spreadProdMenu})}>
                { hasBread ? <YQBread {...breadProps} />: null }
                <Content>{ hasPermission ? children : <Error /> }</Content>
              </Content>     
            </Layout> 
        	</Layout>
        </Layout>
      </div>
    </LocaleProvider>
  )
}

App.propTypes = {
  children: PropTypes.element.isRequired,
  location: PropTypes.object,
  dispatch: PropTypes.func,
  app: PropTypes.object,
  loading: PropTypes.object,
}

export default withRouter(connect(({ app, loading }) => ({ app, loading }))(App))
